<template>
  <div class="moonshot-chat">
    <div class="chat-header">
      <div class="header-left">
        <h3>🌙 Moonshot AI</h3>
        <el-tag type="success" size="small">已连接</el-tag>
      </div>
      <div class="header-right">
        <el-select v-model="selectedModel" size="small" style="width: 180px;">
          <el-option 
            v-for="model in models" 
            :key="model.id"
            :label="model.name" 
            :value="model.id"
          />
        </el-select>
        <el-button size="small" text @click="showSettings = true">
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-content">
          <h4>🌙 欢迎使用 Moonshot AI</h4>
          <p>我是月之暗面的AI助手，擅长：</p>
          <ul>
            <li>💬 智能对话和问答</li>
            <li>💻 代码编写和调试</li>
            <li>📝 文档分析和总结</li>
            <li>🌐 多语言翻译</li>
            <li>✨ 创意写作和润色</li>
          </ul>
          <p>有什么可以帮助您的吗？</p>
        </div>
      </div>

      <!-- 消息列表 -->
      <div 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message', message.role]"
      >
        <div class="message-avatar">
          <el-avatar :size="32">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <span v-else class="moonshot-icon">🌙</span>
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="sender">{{ message.role === 'user' ? '您' : 'Moonshot' }}</span>
            <span class="time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="text" v-html="formatMessage(message.content)"></div>
          <div v-if="message.role === 'assistant'" class="message-actions">
            <el-button size="small" text @click="copyMessage(message.content)">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-button size="small" text @click="regenerateMessage(index)">
              <el-icon><Refresh /></el-icon>
              重新生成
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 正在输入指示器 -->
      <div v-if="isTyping" class="message assistant">
        <div class="message-avatar">
          <el-avatar :size="32">
            <span class="moonshot-icon">🌙</span>
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷功能 -->
    <div class="quick-actions" v-if="!isLoading">
      <el-button 
        v-for="action in quickActions" 
        :key="action.key"
        size="small"
        @click="sendQuickMessage(action.prompt)"
      >
        {{ action.label }}
      </el-button>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="输入您的问题... (Ctrl+Enter发送)"
        @keydown.ctrl.enter="sendMessage"
        :disabled="isLoading"
      />
      <div class="input-actions">
        <div class="input-info">
          <span>字符数: {{ inputMessage.length }}</span>
          <span>模型: {{ getModelName(selectedModel) }}</span>
        </div>
        <div class="action-buttons">
          <el-button 
            size="small" 
            @click="clearMessages"
            :disabled="messages.length === 0"
          >
            清空
          </el-button>
          <el-button 
            type="primary" 
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 设置弹窗 -->
    <el-dialog v-model="showSettings" title="Moonshot AI 设置" width="400px">
      <el-form label-width="80px">
        <el-form-item label="模型">
          <el-select v-model="selectedModel" style="width: 100%">
            <el-option 
              v-for="model in models" 
              :key="model.id"
              :label="model.name" 
              :value="model.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="温度">
          <el-slider 
            v-model="temperature" 
            :min="0" 
            :max="1" 
            :step="0.1" 
            show-input 
          />
          <el-text size="small" type="info">
            较低值使输出更确定，较高值使输出更随机
          </el-text>
        </el-form-item>
        <el-form-item label="最大令牌">
          <el-input-number 
            v-model="maxTokens" 
            :min="100" 
            :max="4000" 
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="流式响应">
          <el-switch v-model="useStream" />
          <el-text size="small" type="info">
            开启后可实时看到AI回复过程
          </el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettings = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Setting, 
  DocumentCopy, 
  Refresh,
  MagicStick,
  EditPen,
  Document
} from '@element-plus/icons-vue'
import moonshotService from '@/utils/moonshotService'

export default {
  name: 'MoonshotChat',
  components: {
    User,
    Setting,
    DocumentCopy,
    Refresh,
    MagicStick,
    EditPen,
    Document
  },
  setup() {
    const inputMessage = ref('')
    const messages = reactive([])
    const models = ref([])
    const selectedModel = ref('moonshot-v1-8k')
    const isLoading = ref(false)
    const isTyping = ref(false)
    const messagesContainer = ref(null)
    const showSettings = ref(false)

    // 设置参数
    const temperature = ref(0.3)
    const maxTokens = ref(2000)
    const useStream = ref(true)

    // 快捷操作
    const quickActions = [
      {
        key: 'code',
        label: '代码助手',
        icon: 'EditPen',
        prompt: '我需要编程方面的帮助，请问有什么可以协助的吗？'
      },
      {
        key: 'translate',
        label: '翻译助手',
        icon: 'Document',
        prompt: '我需要翻译一些文本，请帮助我'
      },
      {
        key: 'summary',
        label: '文档总结',
        icon: 'Document',
        prompt: '请帮我分析和总结文档内容'
      },
      {
        key: 'creative',
        label: '创意写作',
        icon: 'MagicStick',
        prompt: '我需要一些创意写作的帮助'
      }
    ]

    // 加载可用模型
    const loadModels = async () => {
      try {
        const response = await moonshotService.getModels()
        if (response.status) {
          models.value = response.data.map(model => ({
            id: model.id,
            name: model.name || model.id,
            description: model.description
          }))
        }
      } catch (error) {
        console.error('加载模型失败:', error)
        ElMessage.error('加载模型列表失败')
      }
    }

    // 获取模型名称
    const getModelName = (modelId) => {
      const model = models.value.find(m => m.id === modelId)
      return model ? model.name : modelId
    }

    // 发送消息
    const sendMessage = async () => {
      if (!inputMessage.value.trim() || isLoading.value) return

      const userMessage = {
        role: 'user',
        content: inputMessage.value,
        timestamp: new Date()
      }

      messages.push(userMessage)
      const currentInput = inputMessage.value
      inputMessage.value = ''
      
      scrollToBottom()

      try {
        isLoading.value = true
        isTyping.value = true

        // 准备对话历史（最近10条消息）
        const history = messages.slice(-11, -1).map(msg => ({
          role: msg.role,
          content: msg.content
        }))

        // AI回复消息
        let assistantMessage = {
          role: 'assistant',
          content: '',
          timestamp: new Date()
        }
        messages.push(assistantMessage)

        if (useStream.value) {
          // 使用流式响应
          await moonshotService.chatStream(
            {
              message: currentInput,
              history: history,
              model: selectedModel.value,
              config: {
                temperature: temperature.value,
                max_tokens: maxTokens.value
              }
            },
            // onMessage - 接收流式数据
            (content) => {
              assistantMessage.content += content
              scrollToBottom()
            },
            // onComplete - 完成回调
            () => {
              isTyping.value = false
              scrollToBottom()
            },
            // onError - 错误处理
            (error) => {
              console.error('Moonshot响应错误:', error)
              assistantMessage.content = moonshotService.constructor.handleError(error)
              ElMessage.error('AI服务异常')
            }
          )
        } else {
          // 使用普通响应
          const response = await moonshotService.chat({
            message: currentInput,
            history: history,
            model: selectedModel.value,
            config: {
              temperature: temperature.value,
              max_tokens: maxTokens.value
            }
          })

          if (response.status) {
            assistantMessage.content = response.data.content
          } else {
            assistantMessage.content = '抱歉，我现在无法回复您的消息。'
            ElMessage.error('AI响应失败')
          }
          
          isTyping.value = false
        }

      } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
        
        // 更新AI消息为错误信息
        if (messages[messages.length - 1].role === 'assistant') {
          messages[messages.length - 1].content = moonshotService.constructor.handleError(error)
        }
      } finally {
        isLoading.value = false
        isTyping.value = false
      }
    }

    // 发送快捷消息
    const sendQuickMessage = (prompt) => {
      inputMessage.value = prompt
      sendMessage()
    }

    // 重新生成消息
    const regenerateMessage = async (messageIndex) => {
      if (messageIndex <= 0 || messages[messageIndex].role !== 'assistant') return

      const previousUserMessage = messages[messageIndex - 1]
      if (!previousUserMessage || previousUserMessage.role !== 'user') return

      // 临时保存用户消息
      const tempInput = inputMessage.value
      inputMessage.value = previousUserMessage.content

      // 删除当前AI消息及之后的所有消息
      messages.splice(messageIndex)

      // 重新发送
      await sendMessage()

      // 恢复输入框内容
      inputMessage.value = tempInput
    }

    // 复制消息
    const copyMessage = async (content) => {
      try {
        await navigator.clipboard.writeText(content)
        ElMessage.success('已复制到剪贴板')
      } catch (error) {
        ElMessage.error('复制失败')
      }
    }

    // 清空消息
    const clearMessages = () => {
      messages.length = 0
      ElMessage.success('对话已清空')
    }

    // 保存设置
    const saveSettings = () => {
      localStorage.setItem('moonshot_settings', JSON.stringify({
        model: selectedModel.value,
        temperature: temperature.value,
        maxTokens: maxTokens.value,
        useStream: useStream.value
      }))
      showSettings.value = false
      ElMessage.success('设置已保存')
    }

    // 加载设置
    const loadSettings = () => {
      const settings = JSON.parse(localStorage.getItem('moonshot_settings') || '{}')
      if (settings.model) selectedModel.value = settings.model
      if (settings.temperature !== undefined) temperature.value = settings.temperature
      if (settings.maxTokens) maxTokens.value = settings.maxTokens
      if (settings.useStream !== undefined) useStream.value = settings.useStream
    }

    // 格式化消息内容
    const formatMessage = (content) => {
      return content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
        .replace(/\n/g, '<br>')
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      const now = new Date()
      const msgTime = new Date(timestamp)
      const diff = now - msgTime

      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 24小时内
        return msgTime.toLocaleTimeString()
      } else {
        return msgTime.toLocaleDateString()
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    onMounted(() => {
      loadModels()
      loadSettings()
    })

    return {
      inputMessage,
      messages,
      models,
      selectedModel,
      isLoading,
      isTyping,
      messagesContainer,
      showSettings,
      temperature,
      maxTokens,
      useStream,
      quickActions,
      getModelName,
      sendMessage,
      sendQuickMessage,
      regenerateMessage,
      copyMessage,
      clearMessages,
      saveSettings,
      formatMessage,
      formatTime
    }
  }
}
</script>

<style scoped>
.moonshot-chat {
  display: flex;
  flex-direction: column;
  height: 700px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fafbfc;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
}

.welcome-content {
  max-width: 400px;
  margin: 0 auto;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.welcome-content h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 20px;
}

.welcome-content p {
  margin: 12px 0;
  color: #606266;
  line-height: 1.6;
}

.welcome-content ul {
  text-align: left;
  margin: 16px 0;
  padding-left: 20px;
}

.welcome-content li {
  margin: 8px 0;
  color: #606266;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 12px;
}

.moonshot-icon {
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
}

.message-content {
  max-width: 75%;
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  opacity: 0.8;
}

.sender {
  font-weight: 600;
}

.text {
  line-height: 1.6;
  word-wrap: break-word;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { 
    transform: scale(0.8); 
    opacity: 0.5; 
  }
  40% { 
    transform: scale(1); 
    opacity: 1; 
  }
}

.quick-actions {
  display: flex;
  gap: 8px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
  flex-wrap: wrap;
}

.chat-input {
  border-top: 1px solid #e4e7ed;
  padding: 20px;
  background: white;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-info {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 代码块样式 */
:deep(code) {
  background: #f6f8fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 13px;
}

:deep(pre) {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  overflow-x: auto;
  margin: 8px 0;
}

:deep(pre code) {
  background: none;
  padding: 0;
}
</style>
